package com.huilian.iotbox.admin.quartz.job;

import com.huilian.iotbox.admin.service.*;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author 谢洛涛
 * @date 2021/4/21 10:41
 */
@Slf4j
public class StatsOrderMonthJob implements BaseJob {
    /**
     * 场地月统计
     */
    @Autowired
    private StatsAgencyService statsAgencyService;
    @Autowired
    private StatsStoreService statsStoreService;
    @Autowired
    private StatsUserService statsUserService;
    @Autowired
    private ErrorLogCommonService errorLogCommonService;
    @Autowired
    private StatsDeviceService statsDeviceService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        log.info("--------------定时任务 月统计 场地信息、分润 统计开始 时间{}---------------", DateTimeUtils.currTime());
        String startDateStr = DateTimeUtils.getPreviousMonthFirstDay();
        String endDateStr = DateTimeUtils.getPreviousMonthLastDay();
        Exception result = this.doJob(startDateStr, endDateStr);
        if (result != null) {
            errorLogCommonService.writerInfoException("统计失败", null, result);
        }

        log.info("--------------定时任务 月统计 场地信息、分润 统计结束 end时间{}---------------", DateTimeUtils.currTime());
    }

    public Exception doJob(String startDateStr, String endDateStr) {
        Exception temp = null;
        try {
            statsStoreService.statsMonthStoreJob(startDateStr, endDateStr);
            statsUserService.statsMonthUserJob(startDateStr, endDateStr);
            statsAgencyService.statsMonthAgencyJob(startDateStr, endDateStr);
            // 设备月统计
            statsDeviceService.statsMonthDeviceJob(startDateStr, endDateStr, DateTimeUtils.getPreviousMonth());
        } catch (Exception e) {
            e.printStackTrace();
            temp = e;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return temp;
    }
}
